import { fileURLToPath } from 'url'
import { dirname, join } from 'path'
import axios from "axios"
import { promises as fs } from 'fs'

// 文件路径
const __filePath = fileURLToPath(import.meta.url)
// 文件所在目录
const __dirname = dirname(__filePath)

const dataFileName = 'dictData.js'

// 本地数据保存路径
const localDataJSONPath = join(__dirname, dataFileName)

let axiosInstance

// 格式化后端数据
const formatData = data => data.reduce((acc, {dictLabel, dictValue, dictType}) => {
    if (!acc[dictType]) acc[dictType] = {
        isHaveIn: () => {},
        isNotHaveIn: () => {}
    }
    acc[dictType][dictLabel] = dictValue
    return acc
}, {})

// 格式化数据为字符串
const dataToString = data => JSON.stringify(data, (key, value) => {
    if (typeof value === 'function') return '() => {}'
    else return value
}, 2)


// 写入文件
const writeFilePromise = (strData, filePath, beginTime) => {
    const outputContent = `export default ${ strData }`
    fs.writeFile(filePath, outputContent, 'utf-8')
        .then(() => log(beginTime, '字典更新成功'))
        .catch((error) => console.log('字典更新失败:', error))
}
const log = (oldTime, msg) => {
    console.log(msg + ',耗时:', new Date().getTime() - oldTime, 'ms')
}


const dictDataUrl = "/system/dictData/allDictData"

function fetchDataAndWriteToFile(baseURL, filePath = localDataJSONPath) {
    const beginTime = new Date().getTime()
    if (axiosInstance === undefined) axiosInstance = axios.create({
        // axios中请求配置有baseURL选项，表示请求URL公共部分
        baseURL: baseURL,
        // 超时
        timeout: 10000,
    })
    axiosInstance['get'](dictDataUrl).then((res) => {
        const formattedData = formatData(res.data?.data)
        const strData = dataToString(formattedData)
        try {
            // 读取本地数据
            import('./' + dataFileName).then(data => {
                if (dataToString(data.default) !== strData) writeFilePromise(strData, filePath, beginTime)
            })
        } catch (e) {
            console.log('读取本地字典失败,重新写入')
            writeFilePromise(strData, filePath, beginTime)
        }
    }).catch(() => console.log('获取字典数据失败'))
}

export default fetchDataAndWriteToFile
